# -*- coding: utf-8 -*-
# 
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
import json
import os
import locale

# 指定CA证书路径
os.environ['REQUESTS_CA_BUNDLE'] = r'C:\Projekt\VW_10638\translator\PREH-Root-CA01.crt'

class TranslatorApp(App):
    def build(self):
        self.load_config()

        self.layout = BoxLayout(orientation='vertical')
        
        # TextInput for English/German
        # Layout for English/German input and check button
        en_de_layout = BoxLayout(orientation='horizontal', size_hint=(1, 0.5))
        self.input_en_de = TextInput(hint_text='Type some English/German text here...', multiline=False, size_hint=(0.8, 1))
        en_de_layout.add_widget(self.input_en_de)
        
        self.check_button = Button(text='check', size_hint=(0.2, 1))
        self.check_button.bind(on_press=self.check_and_translate)
        en_de_layout.add_widget(self.check_button)
        self.layout.add_widget(en_de_layout)
        
        # Layout for Chinese input and translate button
        zh_layout = BoxLayout(orientation='horizontal', size_hint=(1, 0.5))
        self.input_zh = TextInput(hint_text='Type some Chinese text here...', multiline=False, size_hint=(0.8, 1))
        zh_layout.add_widget(self.input_zh)
        
        self.translate_button = Button(text='translate', size_hint=(0.2, 1))
        self.translate_button.bind(on_press=self.translate_text_to_en)
        zh_layout.add_widget(self.translate_button)
        self.layout.add_widget(zh_layout)
        
        # Button to open config window
        self.config_button = Button(text='cfg')
        self.config_button.bind(on_press=self.open_config_window)
        self.layout.add_widget(self.config_button)
        
        return self.layout
    
    def load_config(self):
        try:
            with open('config.json', 'r') as f:
                self.config = json.load(f)
        except FileNotFoundError:
            self.show_popup('文件未找到', 'config.json 文件未找到')
            self.config = {"safety_key": "", "base_address": "", "model_name": ""}
    
    def save_config(self, config):
        with open('config.json', 'w') as f:
            json.dump(config, f)
    
    def show_popup(self, title, message):
        popup = Popup(title=title,
                      content=Label(text=message),
                      size_hint=(None, None), size=(400, 400))
        popup.open()

    def check_and_translate(self, instance):
        import os
        import dashscope
        
        # 设置API密钥
        dashscope.api_key = self.config["safety_key"] or "sk-07f4d6aa6f2e4acbac21f47ddc07c0e3"
        
        def validate_input(text):
            if not text or text.strip() == "":
                self.show_popup('输入验证错误', "输入不能为空，请提供有效的文本")
        
        def perform_translation(text):
            try:
                # 调用API进行翻译
                response = dashscope.Generation.call(
                    model='qwen2.5-32b-instruct',
                    prompt=f'将以下文本翻译成中文：{text}'
                )
                if response.status_code == 200:
                    return response.output.text
                else:
                    raise RuntimeError(f"翻译失败，错误信息：{response.code} {response.message}")
            except Exception as e:
                self.show_popup('翻译过程中发生错误', f"翻译过程中发生错误：{str(e)}")
        
        try:
            en_de_text = self.input_en_de.text.strip()
            validate_input(en_de_text)
            
            # 执行翻译
            translation_result = perform_translation(en_de_text)
            self.input_zh.text = translation_result
            
        except ValueError as ve:
            print(f'输入验证错误：{ve}')
        except RuntimeError as re:
            print(f'运行时错误：{re}')
        except Exception as e:
            print(f'发生未知错误：{e}')
            
    def translate_text_to_en(self, instance):
        import os
        import dashscope
        
        # 设置API密钥
        dashscope.api_key = self.config["safety_key"] or "sk-07f4d6aa6f2e4acbac21f47ddc07c0e3"
        
        def validate_input(text):
            if not text or text.strip() == "":
                self.show_popup('输入验证错误', "输入不能为空，请提供有效的文本")
        
        def perform_translation(text):
            try:
                # 调用API进行翻译
                response = dashscope.Generation.call(
                    model='qwen2.5-32b-instruct',
                    prompt=f'将以下文本翻译成英文：{text}'
                )
                if response.status_code == 200:
                    return response.output.text
                else:
                    raise RuntimeError(f"翻译失败，错误信息：{response.code} {response.message}")
            except Exception as e:
                self.show_popup('翻译过程中发生错误', f"翻译过程中发生错误：{str(e)}")
        
        try:
            zh_text = self.input_zh.text.strip()
            validate_input(zh_text)
            
            # 执行翻译
            translation_result = perform_translation(zh_text)
            self.input_en_de.text = translation_result.decode('utf-8').encode('gbk')
            
        except ValueError as ve:
            print(f'输入验证错误：{ve}')
        except RuntimeError as re:
            print(f'运行时错误：{re}')
        except Exception as e:
            print(f'发生未知错误：{e}')
            
    def translate_text(self, instance):
        import os
        import dashscope
        
        # 设置API密钥
        dashscope.api_key = self.config["safety_key"] or "sk-07f4d6aa6f2e4acbac21f47ddc07c0e3"
        
        def validate_input(text):
            if not text or text.strip() == "":
                self.show_popup('输入验证错误', "输入不能为空，请提供有效的文本")
        
        def perform_translation(text):
            try:
                # 调用API进行翻译
                response = dashscope.Generation.call(
                    model='qwen2.5-32b-instruct',
                    prompt=f'将以下文本翻译成中文：{text}'
                )
                if response.status_code == 200:
                    return response.output.text
                else:
                    raise RuntimeError(f"翻译失败，错误信息：{response.code} {response.message}")
            except Exception as e:
                self.show_popup('翻译过程中发生错误', f"翻译过程中发生错误：{str(e)}")
        
        try:
            en_de_text = self.input_en_de.text.strip()
            validate_input(en_de_text)
            
            # 执行翻译
            translation_result = perform_translation(en_de_text)
            print(f'翻译结果: {translation_result}')
            
        except ValueError as ve:
            print(f'输入验证错误：{ve}')
        except RuntimeError as re:
            print(f'运行时错误：{re}')
        except Exception as e:
            print(f'发生未知错误：{e}')

    def open_config_window(self, instance):
        from config_window import show_config_window
        show_config_window()

if __name__ == '__main__':
    TranslatorApp().run()